package com.ruyuan.eshop.promotion.service;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.List;

import static com.ruyuan.eshop.common.constants.RocketMqConstant.PLATFORM_PROMOTION_SEND_CONSUMER_GROUP;

/**
 * @author zhonghuashishan
 */
public class TestConsumer {

    public static void main(String[] args) throws InterruptedException, MQClientException {
        // Instantiate with specified consumer group name.
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("test2");

        // Specify name server addresses.
        consumer.setNamesrvAddr("139.224.217.92:9876;106.15.250.248:9876");

        // Subscribe one more more topics to consume.
        consumer.subscribe(PLATFORM_PROMOTION_SEND_CONSUMER_GROUP, "*");
        consumer.setVipChannelEnabled(false);
        // Register callback to execute on arrival of messages fetched from brokers.
        consumer.registerMessageListener(new MessageListenerConcurrently() {

            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
                for (MessageExt messageExt : msgs) {
                    try {
                        String msg = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET).intern();
                        System.out.println(System.currentTimeMillis()+"Receive New Messages: "+msg);
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        //Launch the consumer instance.
        consumer.start();

        System.out.printf("Consumer Started.%n");
    }
}
